package com.mankiw.thead_pool_demo;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

public class MyThreadPool {

    private final int maxSize;

    private final int corePoolSize;

    private final int timeOut;

    private final TimeUnit timeUnit;

    private final BlockingQueue<Runnable> commandList;

    public MyThreadPool(int maxSize,int corePoolSize,int timeout, TimeUnit unit, BlockingQueue<Runnable> commandList) {
        this.maxSize = maxSize;
        this.corePoolSize = corePoolSize;
        this.timeOut = timeout;
        this.timeUnit = unit;
        this.commandList = commandList;
    }



    List<Thread> coreList = new ArrayList<Thread>();

    List<Thread> supportList = new ArrayList<>();

    void execute(Runnable command) {
        if(coreList.size() < corePoolSize) {
            Thread thread = new CoreThread();
            coreList.add(thread);
            thread.start();
        }
        if(commandList.offer(command)) {
           return;
        }
        if(!commandList.offer(command)){
            if(coreList.size() + supportList.size() < maxSize) {
                Thread thread = new SupportThread();
                supportList.add(thread);
                thread.start();
            }
        }

    }

    class CoreThread extends Thread {
        @Override
        public void run() {
            while(true) {
                try {
                    Runnable command = commandList.take();
                    command.run();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    class SupportThread extends Thread {
        @Override
        public void run() {
            while(true) {
                try {
                    Runnable command = commandList.poll(timeOut, timeUnit);
                    if(command == null) {
                        break;
                    }
                    command.run();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            System.out.println("辅助线程结束了");
            System.out.println(Thread.currentThread().getName() + "线程结束了");

        }
    }
}
